<template>
  <div id="#wrap" class="common-containar">
    <!-- 地图 开始-->
    <div class="map_container">
      <div id="container"></div>
      <div id="searchWrap">
        <div class="searchWrap">
          <a-input id="tipinput" type="text" v-model="address" />
          <a-button class="map-btn" type="primary" @click="search">搜索</a-button>
          <a-button class="map-btn" type="primary" @click="mouseMarker">鼠标标点</a-button>
        </div>
        <div id="panel"></div>
      </div>
      <!-- 地图 结束 -->
    </div>
  </div>
</template>

<script>
import { MapLoader, mouseMovingTip, regeoCode, autoComplete, placeSearchBykey } from '@/utils/map/map'

export default {
  name: 'Map',
  data() {
    return {
      map: null,
      AMap: null,
      placeSearch: null,
      address: ''
    }
  },
  mounted() {
    this.$nextTick(function() {
      let that = this
      MapLoader().then(
        AMap => {
          that.map = new AMap.Map('container', {
            center: [114.95901, 44.026942],
            zoom: 12
          })
          that.AMap = AMap
          // 创建搜索服务
          that.placeSearch = new that.AMap.PlaceSearch({
            // panel: 'panel',
            pageSize: 1
          })
          console.log('地图加载成功', AMap)
          // 初始化字段提示
          that.autoCompleteSearch()
        },
        e => {
          console.log('地图加载失败', e)
        }
      )
    })
  },
  methods: {
    // 鼠标点击标点
    mouseMarker() {
      const _this = this
      _this.address = ''
      // 鼠标跟随信息提示
      mouseMovingTip(this)
      // 地图点击标点事件
      _this.AMap.event.addListenerOnce(_this.map, 'click', function(e) {
        // 坐标转换为地址
        regeoCode(_this, e)
        // 清除地图上所有添加的覆盖物
        _this.map.clearMap()
      })
    },
    // 选择地址标点
    autoCompleteSearch() {
      const _this = this
      autoComplete(_this, function(e) {
        _this.placeSearch.setCity(e.poi.adcode)
        _this.address = e.poi.district + e.poi.name
        _this.map.clearMap() // 清除地图上所有添加的覆盖物
        // 关键字查询查询

        placeSearchBykey(_this, e.poi.name)
      })
    },
    handleMap(event, data) {
      this.$emit(event, data)
    },
    search() {
      this.map.clearMap()
      placeSearchBykey(this, this.address) // 关键字查询查询
    }
  }
}
</script>

<style lang="less" scoped>
/* map */
.map_container {
  position: relative;
  height: 100vh;
  background-color: #ffffff;
}
#container {
  height: 90%;
}
.searchWrap {
  position: absolute;
  top: 20px;
  left: 10px;
  display: flex;
}
#tipinput {
  width: 280px;
}
.map-btn {
  margin-left: 10px;
}
</style>
